package gui;

import business.EventManager;
import business.InvitationManager;
import business.UserManager;
import entity.Event;
import entity.Invitation;
import entity.InvitationPK;
import entity.User;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.faces.view.ViewScoped;
import utils.MessageCode;

@Named("invitationBean")
@ViewScoped
public class InvitationBean implements Serializable {
    
    private String sender;
    private String receiver;
    private int eventId;
    private Invitation invitation;
    private boolean viewable = false;
    
    @EJB
    private InvitationManager invitationManager;
    @EJB
    private UserManager userManager;
    @EJB
    private EventManager eventManager;
    
    public InvitationBean() {
    }
    
    public void loadInvitation() {
        InvitationPK key = new InvitationPK(eventId, sender, receiver);
        invitation = invitationManager.find(key);
        if (invitation == null) {
            viewable = true;
        }
        else if (invitation.getReceiver() != null && invitation.getReceiver().equals(userManager.getLoggedUser())) {
            viewable = true;
        }
    }

    public String getSender() {
        return sender;
    }

    public void setSender(String sender) {
        this.sender = sender;
    }

    public String getReceiver() {
        return receiver;
    }

    public void setReceiver(String receiver) {
        this.receiver = receiver;
    }

    public int getEventId() {
        return eventId;
    }

    public void setEventId(int eventId) {
        this.eventId = eventId;
    }

    public Invitation getInvitation() {
        if (invitation == null) {
            invitation = new Invitation();
        }
        return invitation;
    }

    public void setInvitation(Invitation invitation) {
        this.invitation = invitation;
    }
    
    public boolean isViewable() {
        return viewable;
    }
    
    public String accept() {
        User user = userManager.getLoggedUser();
        Event event = eventManager.find(invitation.getEvent().getEventId());
        user.getCalendars().get(0).addEvent(event);
        event.addParticipant(user);
        userManager.save(user);
        eventManager.save(event);
        invitationManager.delete(invitationManager.find(invitation.getInvitationPK()));
        return "log?faces-redirect=true&msgCode=" + MessageCode.INVITATION_ACCEPTED.toString();
    }
    
    public String refuse() {
        invitationManager.delete(invitationManager.find(invitation.getInvitationPK()));
        return "log?faces-redirect=true&msgCode=" + MessageCode.INVITATION_REFUSED.toString();
    }
}